package com.wangxiaonan.speculation.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangxiaonan.speculation.service.QueryService;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 *
 * @Author: wangxiaonan
 * @Date: 2019/7/4
 **/
@Service
public class QueryServiceImpl implements QueryService {

    private static final Logger logger = LoggerFactory.getLogger(QueryServiceImpl.class);
    private static final int RESPONSE_CODE_OK = 200;

    @Resource
    private JestClient jestClient;

    @Override
    public JSONArray queryChartData(String query, Set<String> indicesName, Set<String> typesName) {
        JSONArray array = new JSONArray();
        if (StringUtils.isEmpty(query)) {
            return array;
        }

        logger.info("SearchResult >>>>> ElasticSearch query[{}] indices[{}] type[{}]", query, indicesName, typesName);
        Search search = new Search.Builder(query).addIndices(indicesName).addTypes(typesName).build();
        try {
            SearchResult result = jestClient.execute(search);
            if (result != null && result.getResponseCode() == RESPONSE_CODE_OK) {
                array = JSONObject.parseObject(result.getJsonString()).getJSONObject("aggregations")
                        .getJSONObject("group_by_state")
                        .getJSONArray("buckets");
                array.toArray();
                logger.info("SearchResult >>>>> ElasticSearch [{}]", array.toJSONString());
            } else {
                logger.info("SearchResult >>>>> ElasticSearch 未查到结果 [{}]", result);
            }
        } catch (IOException e) {
            logger.error("SearchResult >>>>> ElasticSearch 查询失败", e);
        }

        return array;
    }

    @Override
    public <T> List<T> queryChartData(Class<T> clazz, Map<String, String> param, Set<String> indicesName,
            Set<String> typesName) {
        return null;
    }
}
